package cn.whdreamblog.action;

import java.util.List;

import net.sf.json.JSONArray;
import cn.ccit.model.BaseModel;
import cn.whdreamblog.entites.Message;
import cn.whdreamblog.entites.PageBean;
import cn.whdreamblog.iservers.IMessageServers;
import cn.whdreamblog.servers.MessageServers;

import com.opensymphony.xwork2.ModelDriven;

public class MessageAction extends BaseAction implements ModelDriven<Message>{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Message msg=new Message(); 
	private JSONArray root=null;
	private String hint="";
	private IMessageServers imservers=new MessageServers();
	private static final int DEFAULT_COMMENT_CODE = -1;
	public String requestMsgList(){
		try {
			this.sendMsgList(startId, limit, msg.getBlogArticleId());
		} catch (Exception e) {
			LOG.error("requestMsgList:",e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	public String requestMsgListByPage(){
		try {
		PageBean p =imservers.getAllMessages2Map(page, limit, msg.getBlogArticleId());
		sendJsonData(p!=null,new BaseModel<PageBean>(), p );
		} catch (Exception e) {
			LOG.error("requestMsgListByPage:",e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	private void sendMsgList(int start,int limit , int blogId) {
		List<Message> msgList=imservers.getSomeMessages(start,limit,blogId);
		BaseModel<List<Message>> baseModel = new BaseModel<List<Message>>();
		baseModel.setData(msgList);
		sendJsonDataList(baseModel);
	}
	public String addMsg(){
		try {
		boolean flag = imservers.insertMessage(msg);
		if(msg.getBlogArticleId() == DEFAULT_COMMENT_CODE){
			sendJsonData(flag, new BaseModel<Message>());
		}else{
			this.sendMsgList(startId, 10, msg.getBlogArticleId());
		}
			
		} catch (Exception e) {
			LOG.error("addMsg:",e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String removeMsg(){
		try {
			sendJsonData(imservers.deleteMessage(msg), new BaseModel<Message>());
		} catch (Exception e) {
			LOG.error("removeMsg:",e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	
	public String requestMessageById() {
		try {
			Message temp=imservers.getMessageById(msg);
			sendJsonData(temp!=null, new BaseModel<Message>(),temp);
		} catch (Exception e) {
			LOG.error("requestMessageById:",e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@Override
	public Message getModel() {
		return msg;
	}
	public JSONArray getRoot() {
		return root;
	}
	public void setRoot(JSONArray root) {
		this.root = root;
	}
	public String getHint() {
		return hint;
	}
	public void setHint(String hint) {
		this.hint = hint;
	}
	
}
